package com.live.http.client.study;

import java.io.InputStream;

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

public class RequestResponseExecution {

	public static void main(String[] args) throws Exception {
		requestExecution();
	}

	public static void requestExecution() throws Exception {
		String url = "http://mu.e.labi.com";
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		HttpResponse response = httpClient.execute(httpGet);
		// printResponseEntity(response);
		printResponseHeader(response);
	}

	// =============================================================================
	public static void printResponseEntity(HttpResponse response)
			throws Exception {
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			InputStream stream = entity.getContent();
			int len;
			byte[] tmp = new byte[2048];
			while ((len = stream.read(tmp)) != -1) {
				System.out.println(new String(tmp, 0, len));
			}

			System.out.println("==============================");
		}
	}

	public static void printResponseHeader(HttpResponse response)
			throws Exception {
		Header[] headers = response.getAllHeaders();
		if (headers != null) {
			for (Header header : headers) {
				System.out.println(header.getName() + ":" + header.getValue());
				HeaderElement[] headerElements = header.getElements();
				if (headerElements != null) {
					System.out.println("the length is " + headerElements.length);
					System.out.println(headerElements);
					// for (HeaderElement element : headerElements) {
					// element.get
					// }
				}
				System.out.println("-----------------------------");
			}
		}
	}

}
